from django.shortcuts import render, redirect, get_object_or_404
from django.contrib import messages
from django.db.models import Q, Count, F
from django.http import JsonResponse
from datetime import datetime, timedelta, date
from .models import Room, Booking, Contact, Amenity


def update_rooms_count_from_orders():
    """从订单表读取数据,更新房间表中的count字段"""
    thirty_days_ago = datetime.now() - timedelta(days=30)
    
    # 获取最近30天的订单数据,按房间分组计数
    bookings = Booking.objects.filter(
        created_at__gte=thirty_days_ago
    ).exclude(status='cancelled').values('room').annotate(
        booking_count=Count('id')
    )
    
    # 更新每个房间的count值
    for booking in bookings:
        Room.objects.filter(id=booking['room']).update(
            count=F('count') + booking['booking_count']
        )


def health_check(request):
    """健康检查端点"""
    return JsonResponse({'status': 'healthy', 'timestamp': datetime.now().isoformat()})


def index(request):
    """主页"""
    update_rooms_count_from_orders()
    
    # 获取精选房间(3个),按count降序,优先展示预订次数多的
    featured_rooms = Room.objects.filter(status='available').order_by('-count')[:3]
    
    return render(request, 'index.html', {
        'featured_rooms': featured_rooms
    })


def about(request):
    """关于我们页面"""
    return render(request, 'about.html')


def rooms(request):
    """房间列表页面 - 带有基础推荐算法"""
    update_rooms_count_from_orders()
    
    # 获取筛选参数
    room_type = request.GET.get('type', 'all')
    capacity = request.GET.get('capacity', 'all')
    sort_by = request.GET.get('sort', 'popularity')
    
    # 构建查询
    query = Room.objects.all()
    
    if room_type != 'all':
        query = query.filter(room_type=room_type)
    
    if capacity != 'all':
        if capacity == '4':
            query = query.filter(capacity__gte=4)
        else:
            query = query.filter(capacity=capacity)
    
    # 添加排序条件
    if sort_by == 'popularity':
        query = query.order_by('-count')
    elif sort_by == 'price_asc':
        query = query.order_by('price')
    elif sort_by == 'price_desc':
        query = query.order_by('-price')
    elif sort_by == 'newest':
        query = query.order_by('-created_at')
    
    # 分页处理
    from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
    page_number = request.GET.get('page', 1)
    paginator = Paginator(query, 6)  # 每页6个房间
    
    try:
        page_obj = paginator.get_page(page_number)
    except PageNotAnInteger:
        page_obj = paginator.get_page(1)
    except EmptyPage:
        page_obj = paginator.get_page(paginator.num_pages)
    
    return render(request, 'rooms.html', {
        'rooms': query,  # 所有房间(用于搜索)
        'page_obj': page_obj,  # 分页对象
        'current_rooms': page_obj.object_list,  # 当前页的房间
        'current_type': room_type,
        'current_capacity': capacity,
        'current_sort': sort_by
    })


def room_detail(request, room_id):
    """房间详情页面"""
    room = get_object_or_404(Room, id=room_id)
    
    # 获取房间设施并按类别分组
    room_amenities = Amenity.objects.filter(roomamenity__room=room).order_by('category', 'name')
    
    # 按类别分组设施
    amenity_categories = {}
    for amenity in room_amenities:
        category = amenity.get_category_display()
        if category not in amenity_categories:
            amenity_categories[category] = []
        amenity_categories[category].append(amenity)
    
    # 获取相关推荐房间 - 优先推荐同类型且热门的房间
    related_rooms = Room.objects.filter(
        status='available',
        room_type=room.room_type
    ).exclude(id=room_id).order_by('-count')[:2]
    
    # 生成未来30天的日期供预订查询
    today = date.today()
    available_dates = []
    for i in range(30):
        current_date = today + timedelta(days=i)
        # 这里简化处理,实际应查询订单表判断是否可预订
        available = True if i % 7 != 0 else False
        
        available_dates.append({
            'date': current_date,
            'available': available,
            'is_today': current_date == today
        })
    
    return render(request, 'room_detail.html', {
        'room': room,
        'amenity_categories': amenity_categories,
        'related_rooms': related_rooms,
        'available_dates': available_dates,
        'today': today
    })


def cuisine(request):
    """美食页面"""
    return render(request, 'cuisine.html')


def facility(request):
    """设施页面"""
    return render(request, 'facility.html')


def access(request):
    """交通页面"""
    return render(request, 'access.html')


def contact(request):
    """联系我们页面"""
    if request.method == 'POST':
        name = request.POST.get('name')
        email = request.POST.get('email')
        phone = request.POST.get('phone')
        subject = request.POST.get('subject')
        message = request.POST.get('message')
        
        # 保存留言到数据库
        try:
            Contact.objects.create(
                name=name,
                email=email,
                phone=phone,
                subject=subject,
                message=message
            )
            messages.success(request, '感谢您的留言,我们会尽快回复您!')
        except Exception as e:
            messages.error(request, f'提交失败:{str(e)}')
        
        return redirect('contact')
    
    # 获取联系信息
    contact_info = Contact.objects.first()
    
    return render(request, 'contact.html', {
        'contact_info': contact_info
    })